package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func main() {
	p1 := ListNode{
		0, &ListNode{
			2, &ListNode{
				4, &ListNode{
					6, nil,
				},
			},
		},
	}
	fmt.Println(displayListNode(&p1))
	res := deleteNode(&p1, 6)
	fmt.Println(displayListNode(res))
}

//
//  deleteNode
//  @Description: 删除链表中值为val的第一个节点
//  @param head: 链表的头指针
//  @param val: 要删除的值
//  @return *ListNode: 删除后的链表对应的头指针
//
func deleteNode(head *ListNode, val int) *ListNode {
	if head == nil {
		return nil
	}
	// 慢指针的next指向原链表的头
	slow := &ListNode{
		0,
		head,
	}
	target := slow
	// 快指针指向链表的头
	fast := head
	for fast != nil {
		if fast.Val == val {
			slow.Next = fast.Next
		}
		fast = fast.Next
		slow = slow.Next
	}
	return target.Next
}

func displayListNode(root *ListNode) []int {
	if root == nil {
		return nil
	}
	var ans []int
	for root != nil {
		ans = append(ans, root.Val)
		root = root.Next
	}
	return ans
}
